import requests
import urllib3

class RestApiRequest:
    def __init__(self) -> None:
        self.session = requests.Session()
    
    def post(self, url, authorization, path, action, body):
        url = url + '/' + path + '/' + action
        header = {
            'authorization': authorization,
            'Content-Type': 'application/json'
        }
        return self.request(url=url, method='post', headers=header, data=body, isJson = True) 
    
    def get(self, url, authorization, path, action, params):
        url = url + '/' + path + '/' + action
        header = {
            'authorization': authorization
        }
        return self.request(url=url, method="get", headers=header, params = params)
    
    def request(self, url, method='get', headers=None, params=None, data=None, isJson = False):
        '''
        定义一个请求方法
        :param url: 域名接口
        :param method: 请求方法
        :param headers: 请求头
        :param param: get请求体
        :param data: post表单请求体
        :param is_json: 是否为json请求数据
        :return: 请求结果
        '''
        if method.lower() == 'get':
            res = self.session.get(url=url, headers=headers, params=params, data=data)
            return res
        elif method.lower()== 'post':
            if isJson:
                res = self.session.post(url=url, headers=headers, json=data)
                return res
            else:
                res = self.session.post(url=url, headers=headers, data=data)
                return res
        elif method.lower() == 'delete':
                res = self.session.delete(url=url, headers=headers)
                return res
        else:
            raise Exception('{} method is not supported.'.format(method))
              
    
    def close(self):
        self.session.close()
    
